//
//  CommonDao.m
//  MyNotes
//
//  Created by chen on 17/3/30.
//  Copyright © 2017年 chen. All rights reserved.
//

#import "CommonDao.h"


#define DBFILE_NAME @"NotesList.db"
@interface CommonDao(){
    sqlite3 *db;
}

@end

@implementation CommonDao

-(void)openDatabase{
    //设置文件名
    NSString *filename = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingString:DBFILE_NAME];
    //打开数据库文件，如果没有就自动创建一个文件
    NSInteger result = sqlite3_open(filename.UTF8String, &db);
    if (result == SQLITE_OK) {
        NSLog(@"打开数据库成功!");
        //创建一个数据库表
        char *errmsg = NULL;
        sqlite3_exec(db, "CREATE TABLE IF NOT EXISTS Note(cid integer primary key autoincrement, name text, age integer)", NULL, NULL, &errmsg);
        if (errmsg) {
            NSLog(@"错误：%s",errmsg);
        }else{
            NSLog(@"建表成功");
        }
    }else{
        NSLog(@"打开数据库失败");
    }
}
-(void)insertData{
    NSString *nameStr;
    NSInteger age;
    for (NSInteger i = 0; i < 1000; i++) {
        nameStr = [NSString stringWithFormat:@"Bourne-name%d",arc4random_uniform(1000)];
        age = arc4random_uniform(80) + 20;
        NSString *sql = [NSString stringWithFormat:@"INSERT INTO Note(name,age) VALUES('%@','%ld')",nameStr,age];
        char *errmsg = NULL;
        sqlite3_exec(db, sql.UTF8String, NULL, NULL, &errmsg);
        if (errmsg) {
            NSLog(@"错误：%s",errmsg);
        }
    }
    NSLog(@"1000数据插入完毕");
}
-(NSInteger)readData{
    NSMutableArray *mArray = [NSMutableArray arrayWithCapacity:1000];
    char *sql = "select name, age from Note;";
    sqlite3_stmt *stmt;
    NSInteger result = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
    if (result == SQLITE_OK) {
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            char *name = (char *)sqlite3_column_text(stmt, 0);
            NSInteger age = sqlite3_column_int(stmt, 1);
            //创建对象
            Person *person = [Person personWithName:[NSString stringWithUTF8String:name] Age:age];
            [mArray addObject:person];
        }
    }
    NSInteger count = [mArray count];
    NSLog(@"当前Note表中的数据为:%ld",count);
    sqlite3_finalize(stmt);
    return count;
}

@end
